<template>
  <div class="departments">
    <el-card>
      <template #header>
        <div>组织架构</div>
      </template>
      <div style="width: 80%; margin: 0 auto">
        <tree-item :data="tData" @getData="getData" />
        <hr>
        <el-tree :data="data" :props="{ label: 'name' }" default-expand-all>
          <template v-slot="{ data }">
            <tree-item :data="data" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <add :init-data="initData" />
  </div>
</template>

<script>
import { companydepartment } from '@/api/departments'
import TreeItem from './compontents/TreeItem.vue'
import Add from './compontents/Add.vue'
export default {
  components: { TreeItem, Add },
  data() {
    return {
      data: [],
      initData: [],
      tData: {
        id: '',
        name: '',
        manager: '负责人',
        top: true
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const { data } = await companydepartment()
      this.tData.name = data.companyName
      this.data = this.treeData(data.depts)
      this.initData = data.depts
    },
    treeData(arr, str = '') {
      return arr.filter((val) => {
        if (val.pid === str) {
          val.children = this.treeData(arr, val.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 15px;
}
</style>
